package dao

import (
	"MobilePackagePromotions/internal/model"

	"context"
	"fmt"
	"github.com/go-kratos/kratos/pkg/log"
	"time"
)

func (d *dao) AddOrder(c context.Context, mobile string, promotions_id int, promotions_content string, status int) (order *model.Order, err error) {
	querySql := fmt.Sprintf("INSERT INTO `order`(`mobile`,`promotions_id`,`promotions_content`,`create_time`,`status`) VALUES(?,?,?,?,?);")

	timenow := time.Now().Format("2006-01-02 15:04:05")
	res, err := d.db.Exec(c, querySql, mobile, promotions_id, promotions_content, timenow, status)
	if err != nil {
		log.Error("db.Exec(%s) error(%v)", querySql, err)
		return nil, err
	}
	order = new(model.Order)
	order.ID, _ = res.LastInsertId()
	order.Mobile = mobile
	order.PromotionsId = promotions_id
	order.CreateTime = timenow
	order.Status = status

	return
}

func (d *dao) GetOrderList(c context.Context, mobile string) (orderlist []*model.Order, err error) {
	querySql := fmt.Sprintf("SELECT * FROM `order` WHERE `mobile`=? ORDER BY `id` DESC;")

	rows, err := d.db.Query(c, querySql, mobile)
	if err != nil {
		log.Error("query  error(%v)", err)
		return
	}
	defer rows.Close()

	orderlist = make([]*model.Order, 0)
	for rows.Next() {
		order := new(model.Order)

		if err = rows.Scan(&order.ID, &order.Mobile, &order.PromotionsId, &order.PromotionsContent, &order.CreateTime, &order.Status); err != nil {
			log.Error("scan demo log error(%v)", err)
			return
		}
		orderlist = append(orderlist, order)
	}

	return
}
